import 'dart:convert';
import 'dart:io';
import 'dart:ui';
import 'package:crypto/crypto.dart';
import 'package:device_info/device_info.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:wu_you/widgets/loading_view.dart';
import 'package:package_info/package_info.dart';
import 'package:toast/toast.dart';

import 'error_handler.dart';

class Utils {
  static String getImgPath(String name, {String format: 'png',String directory}) {
    if(directory != null){
      return 'assets/images/$directory/$name.$format';
    }
    return 'assets/images/$name.$format';
  }

  static DeviceInfoPlugin _deviceInfoPlugin = DeviceInfoPlugin();


  static Future<String> getDeviceId() async {
    if (Platform.isAndroid) {
      AndroidDeviceInfo androidDeviceInfo = await _deviceInfoPlugin.androidInfo;
      String androidId = androidDeviceInfo.androidId;
      if (androidId.length == 16) {
        return androidDeviceInfo.androidId;
      } else {
        return md5.convert(utf8.encode(androidId)).toString().substring(0, 16);
      }
    }
    if (Platform.isIOS) {
      IosDeviceInfo iosDeviceInfo = await _deviceInfoPlugin.iosInfo;
      return iosDeviceInfo.identifierForVendor;
    }
    return '';
  }

  static Future<Map<String, String>> getDeviceInfo() async {
    Map<String, String> map = {};
    String brand;
    String deviceModel;
    String isPhysicalDevice;
    if (Platform.isAndroid) {
      AndroidDeviceInfo deviceInfo = await _deviceInfoPlugin.androidInfo;
      brand = deviceInfo.brand;
      deviceModel = deviceInfo.model;
      isPhysicalDevice = deviceInfo.isPhysicalDevice.toString();
      map['osVersion'] = deviceInfo.version.sdkInt.toString();
    } else if (Platform.isIOS) {
      IosDeviceInfo deviceInfo = await _deviceInfoPlugin.iosInfo;
      brand = deviceInfo.model;
      deviceModel = deviceInfo.utsname.machine;
      isPhysicalDevice = deviceInfo.isPhysicalDevice.toString();
      map['osVersion'] = Platform.operatingSystemVersion;
    }
    PackageInfo packageInfo = await PackageInfo.fromPlatform();
    map['appName'] = packageInfo.packageName;
    map['appVersion'] = packageInfo.version;
    map['osType'] = Platform.operatingSystem;
    map['brand'] = brand;
    map['deviceModel'] = deviceModel;
    map['isPhysicalDevice'] = isPhysicalDevice;
    map['deviceId'] = await getDeviceId();
    return map;
  }
  static var lastPopTime = DateTime.now();
  static avoidRepeatedClicks({int second = 2,dynamic function}){
    if(lastPopTime == null || DateTime.now().difference(lastPopTime) > Duration(seconds: second)){
      lastPopTime = DateTime.now();
      function();
    }
  }

  static Widget getSusItem(BuildContext context, String tag,
      {double susHeight = 40}) {
    if (tag == '★') {
      tag = '★ 热门城市';
    }
    return Container(
      height: susHeight,
      width: MediaQuery.of(context).size.width,
      padding: EdgeInsets.only(left: 16.0),
      color: Color(0xFFF3F4F5),
      alignment: Alignment.centerLeft,
      child: Text(
        '$tag',
        softWrap: false,
        style: TextStyle(
          fontSize: 14.0,
          color: Color(0xFF666666),
        ),
      ),
    );
  }
  static void showSnackBar(BuildContext context, String msg) {
    ScaffoldMessenger.of(context).showSnackBar(
      SnackBar(
        content: Text(msg),
        duration: Duration(seconds: 2),
      ),
    );
  }


  static String getTaskScreen(List list){
    List tempList = List();
    String str = '';
    list.forEach((f){
      tempList.add(f);
    });
    tempList.forEach((f){
      if(str == ''){
        str = "$f";
      }else {
        str = "$str"",""$f";
      }
    });
    return str;
  }

  static bool copy(String text){
    ClipboardData data = new ClipboardData(text: text);
    Clipboard.setData(data);
    return true;
  }
  static bool isChinese(String value) {
    return RegExp(r"[\u4e00-\u9fa5]").hasMatch(value);
  }
  static bool isIdCard(String value) {
    return RegExp(r"^[ZA-ZZa-z0-9_]+$").hasMatch(value);
  }
  static bool isTourist({bool open = true}){
    // return true;
    if(Platform.isIOS && open){
      return true;
    }else{
      return false;
    }
  }



  ///超过四位数的数字转化为w格式,如：38128 => 3.8w，381285 => 38.1w
  static String formatLuckCharCount(int count) {
    if (count <= 0 || count.isNaN) {
      return '0';
    }
    String strCount = count.toString();
    if(strCount.length >= 5) {
      if(strCount.length >= 9){ //亿
        String prefix = strCount.substring(0,strCount.length-8);
        if(strCount.length == 9){
          prefix += '.${strCount[1]}';
        }else if(strCount.length == 10){
          prefix += '.${strCount[2]}';
        }else if(strCount.length == 11){
          prefix += '.${strCount[3]}';
        }else if(strCount.length == 12){
          prefix += '.${strCount[4]}';
        }
        return prefix + '亿';
      }else{
        String prefix = strCount.substring(0,strCount.length-4);
        if(strCount.length == 5) {
          prefix += '.${strCount[1]}';
        }
        if(strCount.length == 6) {
          prefix += '.${strCount[2]}';
        }
        return prefix + '万';
      }
    }
    return strCount;
  }




  static String moneyFormat(double money) {
    if (money < 1000) {
      return formatNum(money);
    } else if (1000 <= money && money < 1000000) {
      return '${formatNum((money / 1000))}K';
    } else if (money > 1000000 && money < 1000000000) {
      return '${formatNum((money / 1000000))}M';
    } else if (money >= 1000000000 && money < 1000000000000) {
      return '${formatNum(money / 1000000000)}B';
    } else if (money > 1000000000000) {
      return '${formatNum(money / 1000000000000)}T';
    }

    return formatNum(money);
  }


  //position是小数点后显示几位
  static String formatNum(dynamic nums, {int postion = 2}) {
    var num;
    if (nums is double) {
      num = nums;
    } else {
      num = double.parse(nums.toString());
    }
    if ((num.toString().length - num.toString().lastIndexOf(".") - 1) < postion) {
      return (num.toStringAsFixed(postion).substring(0, num.toString().lastIndexOf(".") + postion + 1).toString());
    } else {
      return (num.toString().substring(0, num.toString().lastIndexOf(".") + postion + 1).toString());
    }
  }









  static String formatLuckCharCount2(double c) {
    if(c > 10000.0){
      int count = c.round();
      if (count <= 0 || count.isNaN) {
        return '0';
      }
      String strCount = count.toString();
      if(strCount.length >= 5) {
        if(strCount.length >= 9){ //亿
          String prefix = strCount.substring(0,strCount.length-8);
          if(strCount.length == 9){
            prefix += '.${strCount[1]}';
          }else if(strCount.length == 10){
            prefix += '.${strCount[2]}';
          }else if(strCount.length == 11){
            prefix += '.${strCount[3]}';
          }else if(strCount.length == 12){
            prefix += '.${strCount[4]}';
          }
          return prefix + '亿';
        }else{
          String prefix = strCount.substring(0,strCount.length-4);
          if(strCount.length == 5) {
            prefix += '.${strCount[1]}';
          }
          if(strCount.length == 6) {
            prefix += '.${strCount[2]}';
          }
          return prefix + '万';
        }
      }
      return strCount;
    }else{
      return  "$c";
    }
  }
  static String removeAllHtmlTags(String htmlText) {
    RegExp exp = RegExp(
        r"<[^>]*>",
        multiLine: true,
        caseSensitive: true
    );
    return htmlText.replaceAll(exp, '').replaceAll("&nbsp", "").replaceAll("\n", "");
  }


}
class ToastUtils{
  static void show(String msg, BuildContext context,{int dur = 2}) {
    Toast.show(msg, context,gravity: Toast.CENTER,duration: dur);
  }
}
class HexColor extends Color {
  static int _getColorFromHex(String hexColor) {
    hexColor = hexColor.toUpperCase().replaceAll("#", "");
    if (hexColor.length == 6) {
      hexColor = "FF" + hexColor;
    }
    return int.parse(hexColor, radix: 16);
  }

  HexColor(final String hexColor) : super(_getColorFromHex(hexColor));
}

class LoadingApi {
  static dynamic func<T>(Future<T> function, BuildContext context, {Function(T value) complete,Function(String value) error,bool showLoading = true,Color color = Colors.white}) async {

    if(showLoading){ showDialog(context: context, builder: (context) => LoadingView(color: color,), barrierDismissible: false);}
    if(function == null){
      if(showLoading){ Navigator.of(context).pop();};
      return;
    }
  return function.then((value) {
    if(showLoading){ Navigator.of(context).pop();};
      if (complete != null) {
        complete(value);
      }
      return value;
    }).catchError((e) {
    if(showLoading){ Navigator.of(context).pop();};
      ErrorHandler.handleError(e, action: (msg) {
        Toast.show(msg, context,duration: 4);
        error(msg);
      });
      return null;
    });

  }

}
void closeKeyboard(BuildContext context){
  FocusScope.of(context).requestFocus(FocusNode());
}
